在上一篇文章中介紹了 比較查詢運算子 及 邏輯查詢運算子 ,今天接著來介紹 元素查詢運算子 Element Query Operators。
元素查詢運算子有以下兩種:
$exists:判斷 document 是否存在特定 field$type:判斷某個 field 的資料型態是否為某種 BSON type我們直接透過一個範例來介紹 $exists 這個元素查詢運算子。
判斷 inventory 這個 collection 中是否存在 qty 這個欄位 並且 qty 欄位的值不等於5或15
db.inventory.find( { qty: { $exists: true, $nin: [ 5, 15 ] } } )
在官方文檔裡我們可以看到 $type 接受以下的 BSON 資料型態:
| Type | Number | Alias | 
|---|---|---|
| Double | 1 | "double" | 
| String | 2 | "string" | 
| Object | 3 | "object" | 
| Array | 4 | "array" | 
| Binary data | 5 | "binData" | 
| Undefined | 6 | "undefined" | 
| ObjectId | 7 | "objectId" | 
| Boolean | 8 | "bool" | 
| Date | 9 | "date" | 
| Null | 10 | "null" | 
| Regular Expression | 11 | "regex" | 
| DBPointer | 12 | "dbPointer" | 
| Javascript | 13 | "javascript" | 
| Symbol | 14 | "symbol" | 
| Javascript(with scope) | 15 | "javascriptWithScope" | 
| 32-bit integer | 16 | "int" | 
| Timestamp | 17 | "timestamp" | 
| 64-bit integer | 18 | "long" | 
| Decimal128 | 19 | "decimal" | 
| Min key | -1 | "minKey" | 
| Max key | 127 | "maxKey" | 
我們一樣直接透過以下範例來介紹 $type 這個元素查詢運算子。
[
    { "_id" : 1, address : "2030 Martian Way", zipCode : "90698345" },
    { "_id" : 2, address: "156 Lunar Place", zipCode : 43339374 },
    { "_id" : 3, address : "2324 Pluto Place", zipCode: NumberLong(3921412) },
    { "_id" : 4, address : "55 Saturn Ring" , zipCode : NumberInt(88602117) },
    { "_id" : 5, address : "104 Venus Drive", zipCode : ["834847278", "1893289032"]}
]
db.addressBook.find( { "zipCode" : { $type : 2 } } )
db.addressBook.find( { "zipCode" : { $type : "string" } } )
{ "_id" : 1, "address" : "2030 Martian Way", "zipCode" : "90698345" }
{ "_id" : 5, "address" : "104 Venus Drive", "zipCode" : [ "834847278", "1893289032" ] }
db.addressBook.find( { "zipCode" : { $type : 1 } } )
db.addressBook.find( { "zipCode" : { $type : "double" } } )
{ "_id" : 2, "address" : "156 Lunar Place", "zipCode" : 43339374 }
今天簡單介紹了元素查詢運算子,可以透過 $exists 或 $type 來查詢特定元素的結果。明天會介紹最後一種查詢運算子:佇列查詢運算子 Array Query Operators。